/**   
 * Copyright © 2019 哈皮电子商务有限公司. All rights reserved.
 */
package com.happy.main.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.happy.core.dto.DictionaryDTO;
import com.happy.core.dto.DictionaryItemDTO;
import com.happy.core.page.PageList;
import com.happy.core.query.DictionaryItemQuery;
import com.happy.core.query.DictionaryQuery;
import com.happy.main.constant.WebConstants;
import com.happy.main.dictionary.model.DictionaryItemVO;
import com.happy.main.dictionary.model.DictionaryVO;
import com.happy.main.dictionary.service.DictionaryAPIService;
import com.happy.main.pagemodel.BaseResult;
import com.happy.main.pagemodel.PagesResult;
import com.happy.main.pagemodel.ROResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Dictionary;
import java.util.List;

/**
 * @description
 * @author taoxinhuan
 * @date 2019年1月24日 下午9:26:49
 */
@RestController
@Api(value = "字典管理控制器",tags = "字典管理控制器")
public class DictionaryController {
	@Autowired
	private DictionaryAPIService dictionaryAPIService;

	@ApiOperation(value = "更据id获取单个字典",notes = "更据id获取单个字典" )
	@PostMapping("/templates/dictionary/getDictionaryById/{id}")
	public BaseResult getDictionaryById(@PathVariable("id") @ApiParam("字典id") Long id) {
		DictionaryVO dictionaryById = dictionaryAPIService.getDictionaryById(id);
		ROResult<DictionaryVO> result = new ROResult<DictionaryVO>();
		result.setData(dictionaryById);
		result.setResult(WebConstants.RESULT_SUCCESS);
		return result;
	}
	
	@GetMapping("/templates/dictionary/getDictionaryByCode/{code}")
	public BaseResult getDictionaryByCode(@PathVariable("code") String code) {
		DictionaryVO dictionaryById = dictionaryAPIService.getDictionaryByCode(code);
		ROResult<DictionaryVO> result = new ROResult<DictionaryVO>();
		result.setData(dictionaryById);
		result.setResult(WebConstants.RESULT_SUCCESS);
		return result;
	}
	
	@PostMapping("/templates/dictionary/deleteDictionary/{id}")
	public BaseResult deleteDictionary(@PathVariable("id") Long id) {
		dictionaryAPIService.deleteDictionary(id);
		BaseResult result = new BaseResult();
		result.setResult(WebConstants.RESULT_SUCCESS);
		return result;
	}
	
	@PostMapping("/templates/dictionary/insertDictionary")
	public BaseResult insertDictionary(@RequestBody DictionaryDTO record) {
		dictionaryAPIService.insertDictionary(record);
		BaseResult result = new BaseResult();
		result.setResult(WebConstants.RESULT_SUCCESS);
		return result;
	}
	
	@PostMapping("/templates/dictionary/updateDictionary")
	public BaseResult updateDictionary(@RequestBody DictionaryDTO record) {
		dictionaryAPIService.updateDictionary(record);
		BaseResult result = new BaseResult();
		result.setResult(WebConstants.RESULT_SUCCESS);
		return result;
	}
	
	@PostMapping("/templates/dictionary/listDictionary")
	public BaseResult listDictionary(@RequestBody DictionaryQuery query) {
		PageList<DictionaryVO> listDictionary = dictionaryAPIService.listDictionary(query);
		PagesResult<DictionaryVO> result = new PagesResult<DictionaryVO>();
		result.setDatas(listDictionary);
		result.setResult(WebConstants.RESULT_SUCCESS);
		return result;
	}
	
	@PostMapping("/templates/dictionary/deleteDictionaryItem/{id}")
	public BaseResult deleteDictionaryItem(@PathVariable("id") Long id) {
		dictionaryAPIService.deleteDictionaryItem(id);
		BaseResult result = new BaseResult();
		result.setResult(WebConstants.RESULT_SUCCESS);
		return result;
	}
	
	@PostMapping("/templates/dictionary/insertDictionaryItem")
	public BaseResult insertDictionaryItem(@RequestBody DictionaryItemDTO dictionaryItem) {
		dictionaryAPIService.insertDictionaryItem(dictionaryItem);
		BaseResult result = new BaseResult();
		result.setResult(WebConstants.RESULT_SUCCESS);
		return result;
	}
	
	@PostMapping("/templates/dictionary/updateDictionaryItem")
	public BaseResult updateDictionaryItem(@RequestBody DictionaryItemDTO dictionaryItem) {
		dictionaryAPIService.updateDictionaryItem(dictionaryItem);
		BaseResult result = new BaseResult();
		result.setResult(WebConstants.RESULT_SUCCESS);
		return result;
	}
	
	@PostMapping("/templates/dictionary/listDictionaryItem")
	public BaseResult listDictionaryItem(@RequestBody DictionaryItemQuery query) {
		PageList<DictionaryItemVO> listDictionaryItem = dictionaryAPIService.listDictionaryItem(query);
		PagesResult<DictionaryItemVO> result = new PagesResult<DictionaryItemVO>();
		result.setDatas(listDictionaryItem);
		result.setResult(WebConstants.RESULT_SUCCESS);
		return result;
	}

	@GetMapping("/templates/dictionary/export")
	public void export(HttpServletResponse res) {
		try {
			// 第一步，创建一个webbook，对应一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
			String excelName="测试字典";
			//生成一个表格
			HSSFSheet sheet = wb.createSheet(excelName);
			// 第三步，在sheet中添加表头第0行
			HSSFRow row = sheet.createRow(0);

			// 第四步，创建单元格，并设置值表头 设置表头居中
			HSSFCellStyle style = wb.createCellStyle();
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
			HSSFCell cell = row.createCell(0);
			cell.setCellStyle(style);
			cell.setCellValue("字典列表导出结果集");
			DictionaryQuery query = new DictionaryQuery();
			query.setPageIndex(1);
			query.setPageSize(20);
			List<DictionaryDTO> dictionaryDTOS = dictionaryAPIService.listDictionaryDTO(query);
			res.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");
			this.insertData(wb, sheet, row, dictionaryDTOS, res.getOutputStream(), new String[]{"名称", "代码", "序号"});
		} catch (Exception e) {
			System.out.println(e);
		}

	}

	/**
	 * 导入数据到表格中
	 *
	 * @param wb     execl文件
	 * @param sheet  表格
	 * @param row    表格行
	 * @param record 要导出的数据
	 * @param out    输出流
	 */
	private void insertData(HSSFWorkbook wb, HSSFSheet sheet, HSSFRow row, List<DictionaryDTO> record,
							OutputStream out, String[] title) {
		try {
			row = sheet.createRow(1);
			for (int i = 0; i < title.length; i++) {
				row.createCell(i).setCellValue(title[i]);
			}
			for (int i = 0; i < record.size(); i++) {
				row = sheet.createRow(i + 2);
				DictionaryDTO data = record.get(i);
				row.createCell(0).setCellValue(data.getName());
				row.createCell(1).setCellValue(data.getCode());
				row.createCell(2).setCellValue(data.getSequence());
			}
			//合并单元格，前面2位代表开头结尾行，后面2位代表开头结尾列
			CellRangeAddress region = new CellRangeAddress(0, 0, 0, title.length - 1);
			sheet.addMergedRegion(region);
			String savePath="/D:/file_upload/222.xls";
			wb.write(out);
			ByteArrayOutputStream bos=new ByteArrayOutputStream();
			wb.write(bos);
			FileUtils.copyInputStreamToFile(new ByteArrayInputStream(bos.toByteArray()),
					new File(savePath));
             //todo taoxinhuan
			out.flush();
			out.close();
			wb.close();
		} catch (Exception e) {
			System.out.println("导出失败");
		}
	}
}
